<template>
	<view class="bind-email-container">
		<view class="form-card">
			<view class="form-title">绑定邮箱</view>
			<view class="form-desc">绑定邮箱后可使用邮箱和验证码登录</view>
			
			<view class="input-group">
				<text class="label">邮箱地址</text>
				<view class="email-input-wrapper">
					<input class="input email-prefix" type="text" v-model="emailPrefix" placeholder="请输入邮箱前缀" />
					<text class="email-suffix">@163.com</text>
				</view>
			</view>
			
			<view class="input-group">
				<text class="label">验证码</text>
				<input class="input" type="text" v-model="code" placeholder="请输入验证码" maxlength="6" />
				<view class="code-btn" :class="{'disabled': sendingCode}" @click.stop="handleSendCode">
					{{ codeBtnText }}
				</view>
			</view>
			
			<button class="submit-btn" :disabled="!emailPrefix || !code" @click="handleBindEmail">确认绑定</button>
		</view>
		
		<view class="tips-card">
			<view class="tips-title">绑定提示</view>
			<view class="tips-content">
				<view class="tips-item">1. 请确保邮箱地址正确有效</view>
				<view class="tips-item">2. 验证码将发送至您填写的邮箱</view>
				<view class="tips-item">3. 绑定后可使用该邮箱登录</view>
				<view class="tips-item">4. 绑定操作不可逆，请谨慎操作</view>
			</view>
		</view>
		
		<!-- 调试信息区 -->
		<view v-if="DEBUG" class="debug-card">
			<view class="debug-title">调试信息</view>
			<view class="debug-item">邮箱: {{fullEmail}}</view>
			<view class="debug-item">API基础URL: {{baseUrl}}</view>
			<view class="debug-item">验证码按钮状态: {{sendingCode ? '倒计时中' : '可点击'}}</view>
			<button class="debug-btn" @click="testClick">测试点击事件</button>
		</view>
	</view>
</template>

<script>
import { BASE_URL } from '@/utils/request';
import { getToken } from '@/utils/auth';

export default {
	data() {
		return {
			emailPrefix: '',
			code: '',
			sendingCode: false,
			countdown: 60,
			timer: null,
			baseUrl: BASE_URL, // 直接从request.js导入
			DEBUG: true // 开启调试模式
		}
	},
	computed: {
		codeBtnText() {
			return this.sendingCode ? `${this.countdown}秒后重新获取` : '获取验证码';
		},
		fullEmail() {
			return this.emailPrefix ? `${this.emailPrefix}@163.com` : '';
		}
	},
	onLoad() {
		// 检查登录状态
		const token = getToken();
		if (!token) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1500);
		}
		
		console.log('页面加载完成，API基础URL:', this.baseUrl);
	},
	beforeDestroy() {
		// 清除定时器
		this.clearTimer();
	},
	methods: {
		// 测试点击事件 - 调试用
		testClick() {
			uni.showToast({
				title: '点击事件正常',
				icon: 'none'
			});
			console.log('测试按钮被点击');
		},
		
		// 清理定时器
		clearTimer() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
		},
		
		// 处理发送验证码
		handleSendCode() {
			console.log('验证码按钮被点击');
			if (this.sendingCode) {
				console.log('正在倒计时中，忽略点击');
				return;
			}
			
			this.sendVerificationCode();
		},
		
		// 发送验证码
		async sendVerificationCode() {
			// 验证邮箱格式
			if (!this.emailPrefix || this.emailPrefix.trim() === '') {
				console.log('邮箱前缀为空，显示提示');
				uni.showToast({
					title: '请输入邮箱前缀',
					icon: 'none'
				});
				return;
			}
			
			try {
				console.log('准备发送验证码');
				uni.showLoading({
					title: '发送中...'
				});
				
				const params = {
					email: this.fullEmail,
					type: 'login'  // 临时使用login类型，避免服务器验证问题
				};
				
				console.log('发送验证码至:', this.fullEmail);
				console.log('请求参数:', JSON.stringify(params));
				console.log('请求URL:', this.baseUrl + '/api/mobile/user/email/verify');
				
				// 使用原生request直接发送请求
				const token = getToken();
				uni.request({
					url: this.baseUrl + '/api/mobile/user/email/verify',
					method: 'POST',
					data: params,
					header: {
						'Content-Type': 'application/json',
						'Authorization': token ? ('Bearer ' + token) : ''
					},
					success: (res) => {
						console.log('验证码请求响应:', JSON.stringify(res));
						uni.hideLoading();
						
						if (res.statusCode === 200) {
							uni.showToast({
								title: '验证码已发送',
								icon: 'success'
							});
							this.startCountdown();
						} else {
							uni.showToast({
								title: (res.data && res.data.message) || '发送失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('验证码请求失败:', JSON.stringify(err));
						uni.hideLoading();
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					},
					complete: () => {
						console.log('验证码请求完成');
					}
				});
			} catch (error) {
				console.error('验证码发送过程出错:', error);
				uni.hideLoading();
				uni.showToast({
					title: '发送失败，请稍后重试',
					icon: 'none'
				});
			}
		},
		
		// 开始倒计时
		startCountdown() {
			this.sendingCode = true;
			this.countdown = 60;
			this.clearTimer(); // 先清除可能存在的定时器
			
			console.log('开始倒计时');
			this.timer = setInterval(() => {
				if (this.countdown > 1) {
					this.countdown--;
				} else {
					this.clearTimer();
					this.sendingCode = false;
					console.log('倒计时结束');
				}
			}, 1000);
		},
		
		// 处理绑定邮箱
		handleBindEmail() {
			console.log('绑定按钮被点击');
			this.bindEmail();
		},
		
		// 绑定邮箱
		async bindEmail() {
			// 表单验证
			if (!this.emailPrefix || this.emailPrefix.trim() === '') {
				uni.showToast({
					title: '请输入邮箱前缀',
					icon: 'none'
				});
				return;
			}
			
			if (!this.code || this.code.length !== 6) {
				uni.showToast({
					title: '请输入6位验证码',
					icon: 'none'
				});
				return;
			}
			
			try {
				uni.showLoading({
					title: '绑定中...'
				});
				
				const params = {
					email: this.fullEmail,
					code: this.code
				};
				
				console.log('绑定邮箱:', this.fullEmail);
				console.log('绑定参数:', JSON.stringify(params));
				
				// 使用原生request
				const token = getToken();
				uni.request({
					url: this.baseUrl + '/api/mobile/user/bind/email',
					method: 'POST',
					data: params,
					header: {
						'Content-Type': 'application/json',
						'Authorization': token ? ('Bearer ' + token) : ''
					},
					success: (res) => {
						console.log('绑定请求响应:', JSON.stringify(res));
						uni.hideLoading();
						
						if (res.statusCode === 200) {
							uni.showToast({
								title: '绑定成功',
								icon: 'success'
							});
							
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						} else {
							uni.showToast({
								title: (res.data && res.data.message) || '绑定失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('绑定请求失败:', JSON.stringify(err));
						uni.hideLoading();
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			} catch (error) {
				console.error('绑定过程出错:', error);
				uni.hideLoading();
				uni.showToast({
					title: '绑定失败，请稍后重试',
					icon: 'none'
				});
			}
		}
	}
}
</script>

<style lang="scss">
.bind-email-container {
	padding: 30rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.form-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 40rpx 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-title {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.form-desc {
	font-size: 28rpx;
	color: #666666;
	margin-bottom: 40rpx;
}

.input-group {
	position: relative;
	margin-bottom: 30rpx;
}

.label {
	display: block;
	font-size: 28rpx;
	color: #333333;
	margin-bottom: 15rpx;
}

.input {
	height: 90rpx;
	padding: 0 30rpx;
	background-color: #f8f8f8;
	border-radius: 45rpx;
	font-size: 30rpx;
}

.email-input-wrapper {
	display: flex;
	align-items: center;
	background-color: #f8f8f8;
	border-radius: 45rpx;
	height: 90rpx;
}

.email-prefix {
	flex: 1;
	background-color: transparent;
	border-radius: 45rpx 0 0 45rpx;
}

.email-suffix {
	padding-right: 30rpx;
	font-size: 30rpx;
	color: #666666;
}

.code-btn {
	position: absolute;
	right: 20rpx;
	bottom: 20rpx;
	height: 50rpx;
	line-height: 50rpx;
	padding: 0 30rpx;
	font-size: 26rpx;
	color: #ffffff;
	background-color: #ff9800;
	border-radius: 25rpx;
	z-index: 10;
}

.code-btn.disabled {
	background-color: #cccccc;
}

.submit-btn {
	margin-top: 50rpx;
	height: 90rpx;
	line-height: 90rpx;
	background-color: #007aff;
	color: #ffffff;
	font-size: 32rpx;
	border-radius: 45rpx;
}

.submit-btn[disabled] {
	background-color: #cccccc;
}

.tips-card {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.tips-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.tips-content {
	padding-left: 20rpx;
}

.tips-item {
	font-size: 28rpx;
	color: #666666;
	line-height: 1.8;
}

/* 调试面板样式 */
.debug-card {
	margin-top: 30rpx;
	background-color: #2c3e50;
	color: #ffffff;
	border-radius: 12rpx;
	padding: 30rpx;
}

.debug-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.debug-item {
	font-size: 24rpx;
	line-height: 1.8;
	font-family: monospace;
	word-break: break-all;
}

.debug-btn {
	margin-top: 20rpx;
	background-color: #3498db;
	color: white;
	font-size: 26rpx;
	height: 70rpx;
	line-height: 70rpx;
}
</style> 